<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
    <!--cityName双向绑定 v-on监听用户退格动作，用于清除天气信息-->
    <input type="text" v-model="cityName" @keyup.delete="isShow=false" @keyup.enter="queryCity()">
    <!--v-on绑定事件-->
    <input type="button" value="查询" @click="queryCity()">
    <br>
    <!--v-for遍历常用城市-->
    <span v-for="city in cities">
        <!--v-on的prevent改变默认行为-->
        <a href="" @click.prevent="queryCityByLink(city)">{{city}}</a>&nbsp;
    </span>
    <hr>
    <!--v-show控制是否显示天气信息-->
    <span v-show="isShow">{{cityName}}：{{weather}}</span>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            cityName: undefined,
            weather: undefined,
            cities: ["成都", "自贡", "郑州", "杭州", "上海"],
            isShow: false
        },
        methods: {
            queryCity() {
                //获取vue对象的this
                var _this = this;
                //axios发送天气查询请求
                axios.get("http://localhost:8080/weather/findByCity?city=" + this.cityName)
                    .then(function (response) {
                        _this.weather = response.data.weatherInfo;
                        if (_this.weather == null) {
                            _this.weather = "没有查询到结果";
                        }
                        _this.isShow = true;
                    }).catch(function (error) {
                    console.log(error);
                })
            },
            //通过点击链接的城市来查询天气
            queryCityByLink(city){
                //先把城市名赋值给data中的cityName，这样就能完成双向绑定
                this.cityName = city;
                //再调用查询天气的方法
                this.queryCity();
            }
        }
    });
</script>
</body>
</html>